package cn.stronglink.assetmanage.business.inspection.view.resiger;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import Scaner.scan.IScanerListener;
import Scaner.scan.TimerInfraraedScaner;
import cn.stronglink.assetmanage.MainActivity;
import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.inspection.adapter.RepairOrderAdapter;
import cn.stronglink.assetmanage.business.inspection.view.PatrolDetail.PatrolDetailFragment;
import cn.stronglink.assetmanage.business.inspection.view.repairDetail.RepairDetailFragment;
import cn.stronglink.assetmanage.business.task.model.ITaskSyncListener;
import cn.stronglink.assetmanage.business.task.model.OrderType;
import cn.stronglink.assetmanage.business.task.model.TaskSyncModel;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.RepailDetailDao;
import cn.stronglink.assetmanage.dao.RepairDao;
import cn.stronglink.assetmanage.dao.SyncTypesDao;
import cn.stronglink.assetmanage.entity.RepailDetail;
import cn.stronglink.assetmanage.entity.Repair;
import cn.stronglink.assetmanage.entity.Room;
import cn.stronglink.assetmanage.entity.SearchAsset;
import cn.stronglink.assetmanage.entity.SyncTypes;
import cn.stronglink.assetmanage.entity.User;
import cn.stronglink.assetmanage.index.entity.PromissionEntity;
import cn.stronglink.assetmanage.index.view.onRecyclerListener;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.assetmanage.widget.CustomProgressDialog;
import cn.stronglink.netrequest.business.repail.RepairService;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


/**
 * 维修登记
 * Created by zhengjinglan on 2018/6/13.
 */

public class RepairRegisterFragment extends Fragment {

    private Button butScanQR;                   //扫码按钮

    private TextView tv_repair_order_name;      // 单号
    private TextView tv_repairRegister_date;    //日期
    private TextView tv_repairRegister_locale;   //地点
    private TextView tv_repairRegister_peple;    //维修人


    private TimerInfraraedScaner scaner;
    private Button save;
    private Repair repair;
    private RecyclerView rv_repairRegister_order_list;
    private List<Room> roomList;
    private List<User> userList;
    private String orderNo;
    private RepairOrderAdapter repairOrderAdapter;
    private List<RepailDetail> repailDetailList;
    private LinearLayoutManager layoutManager;
    private Dialog mDialog;
    private TextView txt_title_left, txt_title_right, txt_main_title;

    private Map<String, RepailDetail> repairNormalMap = new HashMap<>();    //添加到的商品
    private Map<String, SearchAsset> searchAssetSnMap = new HashMap<>();        //根据sn获取资产详情
    private Map<String, SearchAsset> searchAssetRfidMap = new HashMap<>();       //根据rfid获取资产详情

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_repair_register_list, container, false);
        try {
            initData();
            initViewAndData(view);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return view;
    }

    /**
     * 初始化数据
     */
    private void initData() {
        Bundle bundle = getArguments();
        if (bundle == null) {
            Toast.makeText(this.getContext(), "传递的维修单参数为空，无法正常维修", Toast.LENGTH_SHORT).show();
            return;
        }

        String repairId = bundle.getString(Constants.SEARCH_REPAIR_NO);
        if (repairId == null || repairId.isEmpty()) {
            Toast.makeText(this.getContext(), "传递的维修编号为空，无法正常维修", Toast.LENGTH_LONG).show();
            return;
        }

        //获取维修单信息
        List<Repair> repairList = DaoManager.getDaoSession(this.getContext()).getRepairDao().queryBuilder().where(
                RepairDao.Properties.Id_.eq(repairId)).list();

        //获取巡检中的资产详情
        List<RepailDetail> detailList = DaoManager.getDaoSession(this.getContext()).getRepailDetailDao().queryBuilder().where(
                RepailDetailDao.Properties.RepairId_.eq(repairId)
        ).list();
        repailDetailList = detailList;


        //将维修单详情便利到map中，便于快速查找
        for (int i = 0; i < detailList.size(); i++) {
            RepailDetail detail = detailList.get(0);
            repairNormalMap.put(detail.getSerialNo(), detail);
        }
        List<SearchAsset> searchAssetList = DaoManager
                .getDaoSession(this.getContext()).getSearchAssetDao().queryBuilder().list();
        //将巡检资产详情遍历到Map中，便于快速查找
        for (int i = 0; i < searchAssetList.size(); i++) {
            SearchAsset searchAsset = searchAssetList.get(i);
            if (searchAsset.getSerialNo() != null) {
                String rfid = searchAsset.getRfidNo();
                String sn = searchAsset.getSerialNo();
                if (sn != null && !"".equals(sn)) {
                    searchAssetSnMap.put(searchAsset.getSerialNo(), searchAsset);
                }
                if (rfid != null && !"".equals(rfid)) {
                    searchAssetRfidMap.put(searchAsset.getRfidNo(), searchAsset);
                }
            }

        }

    }

    private void initViewAndData(View view) {
        showRepairTitle();
        setOrderBaseData(view);
        txt_title_left = this.getActivity().findViewById(R.id.txt_left_title);
        txt_title_left.setVisibility(View.VISIBLE);
        txt_title_right = this.getActivity().findViewById(R.id.txt_right_title);
        txt_title_right.setVisibility(View.GONE);
        txt_main_title = this.getActivity().findViewById(R.id.txt_main_title);
        txt_main_title.setText("维修登记");

        this.butScanQR = view.findViewById(R.id.btn_patrol_detail_qr);
        this.save = view.findViewById(R.id.btn_repair_register_save);


        this.scaner = new TimerInfraraedScaner(this.getContext());
        this.scaner.setScanerListener(new IScanerListener() {
            @Override
            public void onScaning(List<String> data) {
                //扫描到的sn号码到SearchAsset中去寻找，并将信息保存到RepailDetail表中
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < data.size(); i++) {
                    sb.append(data.get(i) + "   ");
                    String sn = data.get(i);
                    RepairRegisterFragment.this.pushSn(sn);
                }

            }
        });
        this.butScanQR.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (scaner == null) {
                    scaner = new TimerInfraraedScaner(getContext());
                }
                scaner.playSingle();
            }
        });
        this.save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 1.自动 2.离线
                SyncTypes syncType = DaoManager.getDaoSession(getContext()).getSyncTypesDao()
                        .queryBuilder().where(SyncTypesDao.Properties.IsSelected.eq(true)).unique();
                int tp = 0;
                if (syncType != null) {
                    tp = syncType.getSyscTs();
                }
                if (tp == 1) {
                    saveRepairDataWeb();
                } else {
                    saveRepairData();
                }

            }
        });
    }

    private void pushSn(String sn) {
        sn = replaceBlank(sn);
        //判断扫描到的sn或者rfid是否在数据库中
        if (searchAssetSnMap.containsKey(sn)) {
            // 在数据库中存在,跳转到详情页，有sn号
            showRepairDetailFragment(sn);
        } else if (searchAssetRfidMap.containsKey(sn)) {
            //跳转到详情页，有rfid号
            showRepairDetailFragment(sn);
        }
    }


    /**
     * 去掉字符串中\R等
     *
     * @param str
     * @return
     */
    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    private void showRepairTitle() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            String order = bundle.getString(Constants.SEARCH_REPAIR_NO);
            List<Repair> repairList = DaoManager.getDaoSession(this.getActivity()).getRepairDao().queryBuilder().
                    where(RepairDao.Properties.Id_.eq(order)).list();
            if (repairList != null) {
                repair = repairList.get(0);
            }
            orderNo = order;

        }
    }


    private void setOrderBaseData(View view) {
        tv_repair_order_name = view.findViewById(R.id.tv_repair_order_name);
        tv_repairRegister_date = view.findViewById(R.id.tv_operation_date);
        tv_repairRegister_locale = view.findViewById(R.id.tv_repair_location);
        tv_repairRegister_peple = view.findViewById(R.id.tv_repair_operation_user);
        tv_repair_order_name.setText(repair.getId_());
        tv_repairRegister_locale.setText(repair.getRoomName());
        tv_repairRegister_peple.setText(User.getInstance().getName());
        //需要将用户id保存到数据库
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        tv_repairRegister_date.setText(format.format(new Date()));
        rv_repairRegister_order_list = view.findViewById(R.id.rv_patrol_detail_list);
        layoutManager = new LinearLayoutManager(this.getActivity(), LinearLayout.VERTICAL, false);
        rv_repairRegister_order_list.setLayoutManager(layoutManager);
        repairOrderAdapter = new RepairOrderAdapter(this.getActivity());
        rv_repairRegister_order_list.setAdapter(repairOrderAdapter);
        rv_repairRegister_order_list.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        repairOrderAdapter.notifyDatasChanged(repailDetailList);
        repairOrderAdapter.setOnItemClickListener(new onRecyclerListener() {
            @Override
            public void onItemClicked(View v, int postion) {
                orderNo = repailDetailList.get(postion).getRepairId_();
                showRepairDetailFragment(repailDetailList.get(postion).getSerialNo());
            }
        });
    }

    private void showRepairDetailFragment(String serialNo) {

        MainActivity activity = (MainActivity) getActivity();
        PromissionEntity pe = new PromissionEntity();
        pe.setFragment(new RepairDetailFragment());
        pe.setPosition(MainActivity.FRAGMENT_REPAIR_DETAIL_ID);
        pe.setTitle("维修详情");
        //设置传递的数据
        Bundle bundle = new Bundle();
        bundle.putSerializable(Constants.REPAIR_DETAIL_NO, serialNo);
        bundle.putSerializable(Constants.REPAIR_REGISTER_ORDER, orderNo);
        pe.setBundle(bundle);
        activity.onEventRegister(pe);
    }


    //保存本地
    private void saveRepairData() {
        repair.setDetailList(repailDetailList);
        repair.setStatus(Constants.STATUS_THREE);
        DaoManager.getDaoSession(this.getActivity()).getRepairDao().deleteAll();
        DaoManager.getDaoSession(this.getActivity()).getRepairDao().insertOrReplace(repair);
        RepairRegisterFragment.this.getActivity().onBackPressed();
    }

    //上传数据库
    private void saveRepairDataWeb() {
        showProgressDialog("维修单确认中");
        repair.setDetailList(repailDetailList);
        repair.setStatus(Constants.STATUS_THREE);
        TaskSyncModel taskSyncModel = new TaskSyncModel();
        taskSyncModel.setListener(new ITaskSyncListener() {
            @Override
            public void onFail(String orderNo, OrderType orderType, Exception e, int sum) {
                hideProgressDialog();
                ToastUtil.toastShort(e.getMessage());
            }

            @Override
            public void onSucces(String orderNo, OrderType orderType, int sum) {
                hideProgressDialog();
                RepairRegisterFragment.this.getActivity().onBackPressed();
            }
        });
        taskSyncModel.uploadRepair(repair);


    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (scaner != null) {
            this.scaner.stop();
            this.scaner.destory();
        }

    }

    public void showProgressDialog(String msg) {
        mDialog = CustomProgressDialog.createLoadingDialog(getActivity(), msg);
        mDialog.setCancelable(false);
        mDialog.show();
    }

    public void hideProgressDialog() {
        if (mDialog != null) {
            mDialog.cancel();
        }
    }
}
